import axios, { AxiosError, AxiosInstance, AxiosResponse } from 'axios'

class Axios {
  public service: AxiosInstance
  constructor(baseURL: string, timeout: number = 10000) {
    this.service = axios.create({
      baseURL,
      timeout
    })
    this.service.interceptors.request.use(
      (config) => {
        const token = "token"
        if (token) {
          // 携带token
          (config.headers as any).Authorization = `Bearer ${token}`
        }
        return config
      },
      (error) => {
        console.log(error)
        return Promise.reject(error)
      }
    );
    this.service.interceptors.response.use(
      (response: AxiosResponse) => {
        const { code, message , data } = response.data
        if (response.status !== 200) {
          console.log("全局异常");
          return Promise.reject(message)
        }
        if (code === 401) {
          // 401
          return 
        }
        return response.headers['content-disposition'] ? response : data
      },
      (error: AxiosError) => {
        const res = error?.response
        if (res && res.data && res.data instanceof Blob) {
          const reader = new FileReader()
          reader.readAsText(res.data)
          reader.onload = () => {
            const res = JSON.parse(reader.result as string)
            // 异常
          }
          return Promise.reject(error)
        }
        if (res && res.data && (res.data as any).code === 500) {
          // 异常
          return Promise.reject(error)
        }
        if (res && res.status === 500) {
          //  异常
          return Promise.reject(error)
        }
        return Promise.reject(error)
      }
    )
  }
}

const useAxios = (baseURL: string, timeout?: number): AxiosInstance => new Axios(baseURL, timeout).service

const TIME_OUT = 10000
const baseApi = "/api"


export const request = useAxios(baseApi, TIME_OUT)